/**
 * 产品管理分类列表
 * @authors supmain (mtingfeng@gmail.com)
 * @date    2015-01-13 14:18:55
 * @update  2015-01-13 14:18:55
 */
var BSTMG = BSTMG || {};
BSTMG.productmg = {
	$selectors : {},
	flag: { SUBMITTYPE: null , ISUPDATE : true , ISNEWSOFT : true , flag_firstselect : true }, // 0 新增， 1 编辑子分类 ， 2 编辑当前分类 //ISUPDATE 保证分类详情数据只加载一次 //ISNEWSOFT 判断是否是第一次查询  // 默认显示上级分类为input框中的值，第一次加载执行
	init: function(){
		var that = this;
		// 加载动画插件
		BSTMG.plugins.initkittyLoading();
		that.loading = $.kittyLoading();
		/* 选项卡初始化 */
		BSTMG.plugins.prettyTab();
		that.initTabs();
		/* 选择节点保存 */
		that.initSelectors();
		/* 初始化树分类 */
		that.zTreeinit();
		/* 查询 新增 编辑 删除 */
		that.queryAddEditDelete();
		/* 加载分类详情 */
		that.showCategoryDetail();
		
		/* 表格操作 */
		that.tableOperate();
		/* 选择分类产品 */
		that.chooseCategoryProducts();
	},
	initTabs: function(){
		$(".prettyTab").prettyTab({
            current: 0,
            currentClass: 'on'
        });
	},
	/* 展示区块，参数为类名 */
	switchArea: function($area,certain){
		for(var key in $area){
			key == certain ? $area[key].show() : $area[key].hide();
		}
	},
	initSelectors: function(){
		var that = this,
			$selectors = that.$selectors;
			
		$selectors["$categorytable"] = $("#categorytable");
		$selectors["$categorylist"] = $("#categorylist");
		$selectors["$treeDemo"] = $("#treeDemo");
		
		// 第二次改
		$selectors["$categorydetail"] = $("#categorydetail");
		$selectors["$editoperator"] = $("#editoperator");
		$selectors["$tabtable"] = $(".prettyTab").find(".tabtable");
		$selectors["$tabdetail"] = $(".prettyTab").find(".tabdetail");
		$selectors["$operator"] = $("#operator");
		$selectors["$newcategory"] = $("#newcategory");
		$selectors["$sec1"] = $("#sec1");
		$selectors["$sec2"] = $("#sec2");
		// 选项卡区块
		$selectors["switch"] = [];
		$selectors["switch"][1] = {
				"sec1": $selectors["$sec1"],
				"sec2": $selectors["$sec2"]
		};
		// 添加 新增或者编辑 商品分类表单
		$selectors["form_addcategory"] = [];
		var $form_group  = $selectors["$newcategory"].find(".form-group");
		$selectors["form_addcategory"][0] = $form_group.eq(0).find("input");
		$selectors["form_addcategory"][1] = $form_group.eq(1).find("input");
		$selectors["form_addcategory"][2] = $form_group.eq(2).find("input");
		
		//$selectors["form_addcategory"][3] = $form_group.eq(3).find("input");
		$selectors["form_addcategory"][4] = $form_group.eq(4).find("textarea");
		$selectors["form_addcategory"][5] = $form_group.eq(5).find(".btn");	

		// 添加商品分类表单
		$selectors["form_categorydetail"] = [];
		var $form_group  = $selectors["$categorydetail"].find(".form-group");
		$selectors["form_categorydetail"][0] = $form_group.eq(0).find("input");
		$selectors["form_categorydetail"][1] = $form_group.eq(1).find("input");
		$selectors["form_categorydetail"][2] = $form_group.eq(2).find("input");
		
		//$selectors["form_categorydetail"][3] = $form_group.eq(3).find("input");
		$selectors["form_categorydetail"][4] = $form_group.eq(4).find("input");
		$selectors["form_categorydetail"][5] = $form_group.eq(5).find("textarea");
		$selectors["form_categorydetail"][6] = $form_group.eq(6).find(".btn");
	},
	queryAddEditDelete: function(){
		var that = this,
			$selectors = that.$selectors,
			$operator = $selectors["$operator"],
			$editoperator = $selectors["$editoperator"],
			$tabtable = $selectors["$tabtable"],
			$tabdetail = $selectors["$tabdetail"],
			$table = $selectors["$categorytable"],
			$thead = $table.find("thead"),
			$tbody = $table.find("tbody");

		$operator.on("click",".confirmsoft",function(){
			// 查询
		}).on("click",".addcategory",function(){
			// 新增下级分类
			addCategory();
		}).on("click",".editcategory",function(){
			// 编辑子分类
			editCategory();
			//autoCompleteNewCategory(selected[0]);
		}).on("click",".deletecategory",function(){
			// 删除子分类
			deleteCategory();
		});
		
		// 【确定 取消】 新增下级分类或者编辑当前分类  
		$selectors["$newcategory"].on("click",".confirm",function(){			
			var data = checkDataValidity()
			if( !!!data ) { return false; }
			updateOrSaveGoodsType.call(this,data);
			
		}).on("click",".cancel",function(){
			that.switchArea($selectors["switch"][1],'sec1'); //显示选项卡模块
		});
		
		// 【确定 取消】 编辑当前分类 
		$editoperator.on("click",".confirm",function(){
			var data = checkDataValidity()
			if( !!!data ) { return false; }
			updateOrSaveGoodsType.call(this,data);
			
		}).on("click",".cancel",function(){			
			$tabtable.trigger("click");	// 显示表格数据
		});

		// 新增分类 填充数据
		function autoCompleteNewCategory(treeNode){
			if( !treeNode ) { return false; }
			// 填充上级分类名称
			if( treeNode.parentTId ) {
				var parent = treeNode.getParentNode(),
					id = parent.id,
					name = parent.name;
				$selectors["form_addcategory"][2].val(id);
			}else{
				
			}
		};
		// 新增下级分类
		function addCategory(){
			var treeObj = $.fn.zTree.getZTreeObj("treeDemo"),
				selected = treeObj.getSelectedNodes();
			that.flag.SUBMITTYPE = 0;
			that.switchArea($selectors["switch"][1],'sec2'); //显示 新增编辑 模块
			//清空表单数据
			$selectors["form_addcategory"][0].val("");
			$selectors["form_addcategory"][1].val("");
			
			if( selected[0] ){
				var id = selected[0].id,
					name = selected[0].name,
					level = selected[0].level;
				$selectors["form_addcategory"][2].val( name ).data({
					"id" : id ,
					"level" : level,
					"currentTypeId": null
				});
				that.flag.flag_firstselect = true ; // 重新加载默认选中的内容
			};
			
			$selectors["form_addcategory"][4].val("");
		}
		// 编辑子分类
		function editCategory(event){
			var $checkbox = $tbody.find("input.simple").filter(":checked");
			if( $checkbox.length ) {
				var id = $.trim($checkbox.eq(0).attr("data-id")); //获取ID，id应该放在checkbox中
				that.flag.SUBMITTYPE = 1;
				that.switchArea($selectors["switch"][1],'sec2'); //显示 新增编辑 模块		
				var treeNode = $.fn.zTree.getZTreeObj("treeDemo").getNodesByParam("id",id)[0];
				that.autoCompleteCategory.call( $selectors["$newcategory"] , treeNode );	//填充数据				
			}else{
				BSTYUN.dialog.warn("请至少选择一条数据，多条数据默认编辑第一条！");
			}
		};
		// 删除分类
		function deleteCategory(){
			var $checkbox = $tbody.find("input.simple").filter(":checked");
		 	if($checkbox.length){
		 		
		 		BSTYUN.dialog.confirm("确定要删除吗？",function(){
		 			var ids = '';
			 		$checkbox.each(function(index,val){
			 			if(ids == '')
			 				ids = ids + $.trim( $(val).attr("data-id") );
			 			else
			 				ids = ids + ',' + $.trim( $(val).attr("data-id") );
			 		});
		 			//删除方法
		 			$.ajax({
		 				url: '/sysAdmin/operate/goodsTypeAdmin/deleteByTypeId',
		 				type: 'POST',
		 				dataType: 'json',
		 				data: {ids:ids},
		 				beforeSend: function(){
		 					var offset = $selectors["$categorytable"].offset();
		 					loading = new that.loading({coordinate : { x: offset.left , y : offset.top , w : $selectors["$categorytable"].width() , h : $selectors["$categorytable"].height() }});
		 				},
		 				success: function(data){
		 					if(data.isDelete){	 	
		 						var tree = $.fn.zTree.getZTreeObj("treeDemo");
		 						$.each(ids.split(","),function(index,val){
		 							var treenode = tree.getNodesByParam( "id" , val , null)[0];
		 							tree.removeNode( treenode );
		 						});
		 						$checkbox.each(function( index, val ){
		 							$(this).parent().parent().remove();
		 						});
		 						BSTYUN.dialog.ok("删除成功！");
		 					}else{
		 						var isDeleteIds = data.isDeleteIds;
		 						var tree = $.fn.zTree.getZTreeObj("treeDemo");
		 						$.each(isDeleteIds.split(","),function(index,val){
		 							var treenode = tree.getNodesByParam( "id" , val , null)[0];
		 							tree.removeNode( treenode );
		 						});
		 						$checkbox.each(function( index, val ){
		 							var dataid = $.trim( $(this).attr("data-id") );
		 							if( isDeleteIds.indexOf( dataid ) >=0 ){
		 								$(this).parent().parent().remove();
		 							};
		 						});
		 						BSTYUN.dialog.warn("部分节点包含子节点，请删除子节点后，再进行删除操作！<br/>或者部分子节点下挂有商品，请解除关系后再删除！");
		 					}
		 				},
		 				error: function(error){
		 					BSTYUN.dialog.warn("网络异常，请联系管理员");
		 				},
		 				complete: function(){
		 					loading.destory();
		 				}
		 			});
		 		});	
		 	}else{
		 		BSTYUN.dialog.warn("请选择要删除的选项！");
		 	}
		};
		// 数据合法性校验
		function checkDataValidity(){
			var flag = that.flag.SUBMITTYPE,
				cte_no = null,
				cte_name = null,
				cte_parent = null,
				cte_level = null,
				cte_subname = null,
				cte_subpro = null,
				cte_note = null,
				cte_time = null;
				
			switch (flag) {
				case 0 : //新增
					cte_no = $.trim( $selectors["form_addcategory"][0].val() ),
					cte_name = $.trim( $selectors["form_addcategory"][1].val() ),
					
					cte_parent = $.trim( $selectors["form_addcategory"][2].data("id") ),
					cte_level = $.trim( $selectors["form_addcategory"][2].data("level") ),
					
					//cte_subname = $.trim( $selectors["form_addcategory"][3].val() );
					//cte_subpro = $.trim( $selectors["form_addcategory"][3].data("ids") ),
					cte_note = $.trim( $selectors["form_addcategory"][4].val() );
					
					break;
				case 1 : // 编辑子分类
					cte_no = $.trim( $selectors["form_addcategory"][0].val() ),
					cte_name = $.trim( $selectors["form_addcategory"][1].val() ),
					
					//cte_parent = $.trim( $selectors["form_addcategory"][2].val() ),
					//cte_level = $.trim( $selectors["form_addcategory"][2].attr("data-level") ),
					cte_parent = $.trim( $selectors["form_addcategory"][2].data("id") ),
					cte_level = $.trim( $selectors["form_addcategory"][2].data("level") ),
					
					//cte_subname = $.trim( $selectors["form_addcategory"][3].val() );
					//cte_subpro = $.trim( $selectors["form_addcategory"][3].data("ids") ),
					cte_note = $.trim( $selectors["form_addcategory"][4].val() );
					
					break;
				case 2 : // 编辑当前分类
					cte_no = $.trim( $selectors["form_categorydetail"][0].val() ),
					cte_name = $.trim( $selectors["form_categorydetail"][1].val() ),
					
					//cte_parent = $.trim( $selectors["form_categorydetail"][2].val() ),
					//cte_level = $.trim( $selectors["form_categorydetail"][2].attr("data-level") ),
					cte_parent = $.trim( $selectors["form_categorydetail"][2].data("id") ),
					cte_level = $.trim( $selectors["form_categorydetail"][2].data("level") ),
					
					//cte_subname = $.trim( $selectors["form_categorydetail"][3].val() );
					//cte_subpro = $.trim( $selectors["form_categorydetail"][3].data("ids") ),
					cte_time = $.trim( $selectors["form_categorydetail"][4].val() ),
					cte_note = $.trim( $selectors["form_categorydetail"][5].val() );
					break;
				default :
					
					break;
			};			
			var dataobj = {
				cte_no : cte_no,
				cte_name : cte_name,
				cte_parent : cte_parent,
				cte_level: cte_level,
				//cte_subname : cte_subname,
				//cte_subpro : cte_subpro,
				cte_note : cte_note,
				cte_time : cte_time
			}
			var msgobj = {
				cte_no : "商品分类编号",
				cte_name : "商品分类名称",
				cte_parent : "上级分类名称",
				//cte_subname : "选择分类产品ID",
				//cte_subpro : "选择分类产品",
				cte_level : "上级分类ID",
				cte_note : "备注",
				cte_time : "创建时间"	
			}
			switch (flag) {
				case 0:
					for( var key in dataobj ){
						if( key == "cte_time" || key == "cte_note") continue;	// 新增  不校验 创建时间，备注
						if( dataobj[key] == "" ) {
							BSTYUN.dialog.warn( msgobj[key] + "不能为空！" );
							return false;
						}
					};
					break;
				case 1:
					for( var key in dataobj ){
						if( key == "cte_time" || key == "cte_note") continue;	// 编辑子分类  不校验 创建时间，备注
						if( dataobj[key] == "" ) {
							BSTYUN.dialog.warn( msgobj[key] + "不能为空！" );
							return false;
						}
					};
					break;
				case 2:
					for( var key in dataobj ){
						if( key == "cte_time" || key == "cte_note") continue;	// 编辑当前分类  不校验 备注
						if( dataobj[key] == "" ) {
							BSTYUN.dialog.warn( msgobj[key] + "不能为空！" );
							return false;
						}
					};
					break;
			}
			
			return dataobj; //返回校验过的数据
		};
		
		// 新增或者编辑的保存
		function updateOrSaveGoodsType(data){
			// 编辑子分类 或者 编辑当前分类 的ID
			var selectId = $(this).data("categoryid");
				
			var id,parentid;
			if( that.flag.SUBMITTYPE == 0 ){
				//新增父类节点
				parentid = data.cte_parent;
			}else{
				//编辑父类节点
				id = selectId;
			}
			var cte_no = isNaN( data.cte_no ) ? data.cte_no : Number( data.cte_no );
			//判断非负整数（0,1,2,3等）
			if(  cte_no === (cte_no>>>0) ){
				if( cte_no <= 0 || cte_no > 1000){
					return BSTYUN.dialog.warn("商品分类编号为1~1000之间的正整数！");
				}
			}else{
				return BSTYUN.dialog.warn("商品分类编号为1~1000之间的正整数！");
			}
			var level = data.cte_level;
			level = Number(level) + 1;
			var savedata = {
				id : id,
				parentid : data.cte_parent,
				no : data.cte_no,
				name : data.cte_name,
				level : level,
				subname : data.cte_subname,
				subpro : data.cte_subpro,
				note : data.cte_note
			};
			//新增一条数据
			$.ajax({
				type : "POST",
				url : "/sysAdmin/operate/goodsTypeAdmin/saveGoodsType",
				async : false,
				data : savedata,
				dataType: 'json',
				success:function(data){
					if(data.isSuccess) {
						BSTYUN.dialog.ok("新增成功！",function(){
							location.href="/sysAdmin/goodsTypeAdmin/goodsSort";
						});
					}else {
						BSTYUN.dialog.warn("新增失败！请重新保存！");
					}
				}
			})
			
		};

		// 上级分类选择
		var $body = $("body"),
			$selTreeCombine = $(".selTreeCombine"),
			$selbox = $selTreeCombine.find(".seltreebox");
		$selTreeCombine.on("click","input",function(){
			var $this = $(this);
			showCategoryTree.call(this);
			that.flag.flag_firstselect ? fistSelectTreeNode.call(this) : that.flag.flag_firstselect = false ;
		}).on("keydown","input",function(){
			return false;
		});
		// 显示隐藏
		function showCategoryTree() {
			$(this).next(".seltreebox").show();
		};
		// 关闭下拉树
		function onBodyDownCloseTree(event){
			if ( !( $(event.target).parents(".selTreeCombine").length > 0) ) {
				$selbox.hide();
			};
		};
		// 第一次默认选中input内容
		function fistSelectTreeNode(){
			//debugger;
			var $this = $(this),
				id = $this.data("id"),
				ztrrid = $.trim( $this.next().find(".categoryTree").attr("id") ),
				$ztree = $.fn.zTree.getZTreeObj( ztrrid );
			$body.off( "mousedown" , onBodyDownCloseTree );
			if( $ztree.getNodesByParam("id", id )[0] ){
				$("#" + $ztree.getNodesByParam("id", id )[0].tId + '_a').trigger("click");
			};
			$body.on("mousedown" , onBodyDownCloseTree );
			that.flag.flag_firstselect = false ;
		};
	},
	chooseCategoryProducts: function(){
		var $stack = null
		var that = this,
			$selectors = that.$selectors,
			$newcategory = $selectors["$newcategory"],
			$categorydetail = $selectors["$categorydetail"];
		$stack = $newcategory.find(".choosecategory");						// 新增和编辑 选择产品 
		$stack = $categorydetail.find(".choosecategory").add($stack);		// 分类详情 选择产品 
		
		$stack.on("click",".input-group-addon",function(){
			var $input = $(this).prev();
			showCategory.call( $input );
		}).on("click","input.form-control",function(){
			showCategory.call( $(this) );
		}).on("keydown","input.form-control",function(){
			return false;
		});
		
		function showCategory(){
			var $input = this,
				getnewcallback = $.Callbacks();
			var dialog = null;
			var html = '<div id="chooseproduct"><table class="table table-bordered chopdtable"><thead><tr><th><label class="icheck checkall"><input type="checkbox" class="simple"> <span>全选</span></label></th><th>序号</th><th><span class="filter filterno">产品编码</span></th><th><span class="filter filtername">产品名称</span></th></tr></thead><tbody></tbody></table></div>';
			dialog = BSTYUN.dialog.creat({
				id : "categories",
				title: "选择产品",
				content : html,
				top: "58px",
				init: initChooseProducts
			});
			dialog.button(
				{
					name : "获取最新产品列表",
					callback : getNewlyProducts
				},
				{
					name : "确定",
					callback : getConfirmResult
				},{
					name : "取消"
				}
			);
			// 初始化对话框
			function initChooseProducts(){
				var $content = this.DOM.content,
					$thead = $content.find("thead"),
					$tbody = $content.find("tbody");
				// 全选
				$thead.on("click",".checkall",function(){
					var $this = $(this),
						$current = $this.find(".simple"),
						$parent = $this.parents('table.chopdtable'),
						$checkbox = $parent.find('input[type=checkbox]').not($current);
					$current.prop("checked") ? $checkbox.prop("checked",true) : $checkbox.prop("checked",false) ;
				});
				$tbody.on("click","input[type=checkbox]",function(){
					var $this = $(this),
						$all = $this.parents("tbody").eq(0).find("input[type=checkbox]"),
						$checkbox = $all.not($this).filter(":checked");
					var $checkall = $thead.find(".checkall input[type=checkbox]");
					( $this.prop("checked") && ($checkbox.length + 1) == $all.length ) ? $checkall.prop("checked",true) : $checkall.prop("checked",false) ;
				});
				// 获取最新列表
				getnewcallback.add( appenDataToTable );
				// 将ajax获取的数据放入tbody
				function appenDataToTable( data ){
					if(data.isOk){
						var goodsList = data.goodsList;
						var html = '';
						for(var i=0;i<goodsList.length;i++){
							var goods = goodsList[i];
							html += '<tr><td><input type="checkbox" class="simple" ></td>';
							html += '<td class="pronum">'+(i+1)+'</td>';
							html += '<td class="pronum">'+goods.goodsNum+'</td>';
							html += '<td class="proname">'+goods.goodsName+'</td></tr>';
						};
						$tbody.html(html);
						checkSelectedPro();
					}else{
						var $tr = '<tr><td colspan="3"> 查无数据！请添加分类！</td></tr>';
		                $tbody.html($tr);
					};
				};
				// 初始化选中产品
				function checkSelectedPro(){
					var products = $.trim( $input.val() );
					if( !!!products ) { return false ;}
					$.each(products.split(","),function(index,value){
						$tbody.find("td.proname").each(function(sub,va){
							
							var $this = $(this);
							if( value == $.trim( $(this).text() ) ) {
								$this.parent().find("input[type=checkbox]").prop("checked",true);
							};
						});
					});
					var $all = $tbody.find("input[type=checkbox]"),
						$checked = $all.filter(":checked"),
						$checkall = $thead.find(".checkall input[type=checkbox]");
					$all.length == $checked.length ? $checkall.prop("checked",true) : $checkall.prop("checked",false) ;
				};
				// 默认获取最新产品
				getNewlyProducts.apply( this );
			};
			// 获取最新产品列表
			function getNewlyProducts(){
				var $content = this.DOM.content,
					$thead = $content.find("thead"),
					$tbody = $content.find("tbody"),
					loading = null;
				//获取最新产品列表
				$.ajax({
					url: '/sysAdmin/goodsTypeAdmin/selectProductByPortal',
					type: 'post',
					dataType: 'json',
					beforeSend: function(){
						$content.css( {"background": "url(/images/admin/loading_normal.gif) no-repeat center"});
					},
					complete: function(){
						$content.css( {"background": "none"});
					},
					success: function(data){
						getnewcallback.fire( data );
					},
					error: function(){
						BSTYUN.dialog.warn("网络错误，请稍后重试！",function(){
							BSTYUN.dialog.close()
						});
					}
				});
				return false;
			};
			// 确定分类产品，写入input
			function getConfirmResult(){
				var $content = this.DOM.content,
					$thead = $content.find("thead"),
					$tbody = $content.find("tbody");
				var $checkbox = $tbody.find("input.simple").filter(":checked");
				var result = [],
					resultid = [];
				$checkbox.each(function(index,val){
					var $this = $(this),
						txt = $.trim($this.parent().parent().find(".proname").text()),
						id = $.trim($this.parent().parent().find(".pronum").text());
					result.push(txt);
					resultid.push(id);
				});
				// 获取产品的值和id
				$input.val(result.join(",")).data("ids",resultid.join(","));
			};
		};// showCategory 结束
	},
	tableOperate: function(){
		var that = this,
			$selectors = that.$selectors,
			$operator = $selectors["$operator"],
			$table = $selectors["$categorytable"],
			$thead = $table.find("thead"),
			$tbody = $table.find("tbody");
		// 全选
		$thead.on("click",".checkall",function(){
			var $this = $(this),
				$current = $this.find(".simple"),
				$parent = $this.parents('table#categorytable'),
				$checkbox = $parent.find('input[type=checkbox]').not($current);
			$current.prop("checked") ? $checkbox.prop("checked",true) : $checkbox.prop("checked",false) ;
		});
		$tbody.on("click","input[type=checkbox]",function(){
			var $this = $(this),
				$all = $this.parents("tbody").eq(0).find("input[type=checkbox]"),
				$checkbox = $all.not($this).filter(":checked");
			var $checkall = $thead.find(".checkall input[type=checkbox]");
			($this.prop("checked") && ($checkbox.length + 1) == $all.length ) ? $checkall.prop("checked",true) : $checkall.prop("checked",false) ;
		});
	
		// 筛选排序
		$thead.on("click",".filter",function(){
			var $this = $(this),
				$dir = $this.next(),
				index = $this.parents("tr").children().index($this.parent()),
				store = [],
				sift = null,
				desc = $dir.hasClass("fa-sort-desc");
			
			$tbody.find('tr').each(function(sub,val){
				var $tr = $(this),
					txt = $tr.find("td").eq(index).text();
				var obj = {
						tr : $tr,
						txt : txt
				}
				store.push(obj);
			});
			if(desc){
				sift = function(a,b){return a.txt > b.txt ? 1 : -1;}
				$dir.removeClass("fa-sort-desc").addClass("fa-sort-up");
			}else{
				sift = function(a,b){return a.txt > b.txt ? -1 : 1;} 
				$dir.removeClass("fa-sort-up").addClass("fa-sort-desc");
			}
			$.each( store.sort(sift) , function(){
				$tbody.append(this.tr);
			});
		});
		// 查看产品列表 
		$tbody.on("click",".categorylook",function(){
			categoryProductsLook.call( this );
		});
		function categoryProductsLook(){
			var $look = $(this);
			var dialog = null;
			var html = '<div id="productlook"><table class="table table-bordered"><thead><tr><th>产品编码</th><th>产品名称</th></tr></thead><tbody></tbody></table></div>';
			dialog = BSTYUN.dialog.creat({
				id : "productlook",
				title: "已选产品",
				content : html,
				init: initProductLook,
				button:[
					{
						name : "确定",
						callback : null,
						focus: true
					}
				]
			});
			// 初始化对话框
			function initProductLook(){
				var $content = this.DOM.content,
					$thead = $content.find("thead"),
					$tbody = $content.find("tbody");
				var $text = $look.parent().contents().filter(function(){return this.nodeType === 3;}),
					ids = $.trim( $look.attr("data-ids") ).split(","),
					txt = $text.eq(0)[0].nodeValue.split(",");
				var html = '';
				$.each(ids,function(index,val){
					var t1 = val ? val : "",
						t2 = txt[index] ? txt[index] : "";
					html += '<tr><td>'+ t1 +'</td><td>'+ t2 +'</td></tr>';
				});
				$tbody.html(html)
			};
		};
		// 过滤 商品分类名称
		$operator.on("click",".confirmsoft",function(){
			var $this = $(this),
				field = [],
				value = $.trim( $this.prev().val() ),
				$tr = $tbody.find("tr"),
				$troriginal = null,
				originalorder = [],
				$detach =[];
			// 判断是否是新分类 第一次查询
			if( that.flag.ISNEWSOFT ){
				var $temple = $tr.clone();
				$this.data( "original" , $temple );
				$troriginal = $temple;
			}else{
				$troriginal = $this.data( "original" );
			};
			$troriginal.find("td:nth-child(4)").each(function(index,val){
				originalorder.push( $.trim( $(this).text() ) );
			});
			that.flag.ISNEWSOFT = false;
			if( value == "" ){
				if ( $troriginal ){
					$tbody.html( $troriginal );
				};
				return false;
			};
			$.each( originalorder ,function( index , val ){
				if( val.indexOf( value.toLowerCase() ) >=0 || val.indexOf( value.toUpperCase() ) >=0  ){
					$detach.push( $troriginal.eq( index ).clone()  );
					return true;
				};
			});
			if( !!!$detach.length ){
				//BSTYUN.dialog.warn("查无结果！");
				$tbody.html( "<tr><td colspan='6'>查无结果!</td></tr>" );
				return false;
			};
			$tbody.html("");
			$.each( $detach ,function( index , $val ){
				$tbody.append( $val );
			});
		}).on("input onpropertychange ",".softinput",function(){
			$(this).next(".confirmsoft").trigger("click");
		});
	},
	zTreeinit: function(){
		var that = this,
			$body = $("body"),
			$treebox = $("#treeDemo"),
			$tabdetail = that.$selectors["$tabdetail"],
			$tabtable = that.$selectors["$tabtable"];
		var setting = {
				view: {
					showIcon: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onClick: clickTreeNode
				}
			};
		var settingcatogory = {
				view: {
					showIcon: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeClick: checkIsSelf ,
					onClick: setParentCategory
				}
			};
		try{
			var zNodes = SYSTEM.zNodes;
		}catch(e){
			//throw new Error(e);
			if(window && window.console && window.console.warn){
				console.warn(e);
			}
		}
		// 初始化节点
		if($.isArray(zNodes)){
			var ztree = $.fn.zTree.init($treebox, setting, zNodes);
			// 默认选中第一个
			$("#" + $.fn.zTree.getZTreeObj("treeDemo").getNodesByParam("id",-1)[0].tId + '_a').trigger("click");
			// 上级分类树初始化
			$.fn.zTree.init( $("#categoryTree0") , settingcatogory , zNodes );
			$.fn.zTree.init( $("#categoryTree1") , settingcatogory , zNodes );
		}else{
			$(".showcategory").html("<span style='margin-left:20px;'>数据加载出错！</span>");
		};
		// 左侧分类点击事件
		function clickTreeNode(event,treeId,treeNode,clickFlag){
			if( treeNode.parentTId ) {
				// 所有子节点
				$tabdetail.hasClass("disabled") ? $tabdetail.removeClass("disabled") : '' ;
			}else{
				// 根节点
				that.$selectors["$tabdetail"].addClass("disabled");
			}
			that.switchArea(that.$selectors["switch"][1],'sec1'); // 显示选项卡模块
			that.updateCategoryTable(treeNode);					  // 更新右侧表格
			that.flag.ISUPDATE = true;							  // 右侧分类详情可以加载一次数据
			that.flag.ISNEWSOFT = true;							  // 初始化查询条件
			that.flag.flag_firstselect = true;					  // 上级分类 第一次加载默认显示input框中的值
		};
		// 选择上级分类名称
		function setParentCategory( event,treeId,treeNode,clickFlag ){
			var id = treeNode.id ,
				name = treeNode.name ,
				pId = treeNode.pId ,
				level = treeNode.level;
			var $treeinput = $( "#"+treeId ).parent().prev();
			$treeinput.val( name ).data({
				"id" : id ,
				"level" : level
			});
			$body.trigger("mousedown");
		};
		// 选择上级分类 不能为自己
		function checkIsSelf(treeId, treeNode, clickFlag){
			var $treeinput = $( "#"+treeId ).parent().prev(),
				currentTypeId = $treeinput.data("currentTypeId");
			if( treeNode.id == currentTypeId ){
				return false;
			};
		};
	},
	
	showCategoryDetail: function(){
		var that = this,
			$selectors = that.$selectors,
			$tabdetail = $selectors["$tabdetail"];
			$tabdetail.on("click",function(){
				var node = $.fn.zTree.getZTreeObj("treeDemo").getSelectedNodes()[0];
				that.flag.SUBMITTYPE = 2 // 编辑当前分类
				if( that.flag.ISUPDATE ) {
					that.autoCompleteCategory.call(that.$selectors["$categorydetail"],node);
					that.flag.ISUPDATE = false;
				};	
			});	
	},
	/* 编辑商品分类自动补全分类信息 查询详情 ===========================================================================*/
	autoCompleteCategory: function(treeNode,callback){
		var $module = this;
		var that = BSTMG.productmg,
			$box = that.$selectors["$categorydetail"],
			$form = that.$selectors["form_categorydetail"],
			treeRoot = $.fn.zTree.getZTreeObj("treeDemo");
		if( !!!treeNode ) {
			BSTYUN.dialog.warn("当前未找到任务一个节点数据！");
			return false;
		}
		var	id = treeNode.id,
			level = treeNode.level;
		var loading = null;
		$module.find(".confirm").data("categoryid",id);
		
		var params = {
				id: id
		};

		//查询单条数据的详细信息
		$.ajax({
			url: '/sysAdmin/goodsTypeAdmin/selectGoodsTypeInfo',
			type: 'post',
			dataType: 'json',
			data: params,
			beforeSend: function(){
				var offset = $module.find('.formarea').offset();
				if( that.flag.SUBMITTYPE == 2 ) {
					// $.callbacks 回到机制 顺序解决
					offset = {left: 401,top: 175}
				}				
				loading = new that.loading({coordinate : { x: offset.left + 60 , y : offset.top , w : 410 , h : 360}});
			},
			success: function(data){
				var goodsType = data.goodsType,
					cty_no = goodsType.typeNum,
					cty_name = goodsType.typeNum,
					cty_level = goodsType.typeNum;
				// 根据id获取父节点文字内容
				var node = treeRoot.getNodeByParam("id", goodsType.parentId, null),
					parentname = node.name ?  node.name : '';

				switch ( that.flag.SUBMITTYPE ) {
					case 1 :	//新增，编辑子分类
						//商品分类编号
						that.$selectors["form_addcategory"][0].val(goodsType.typeNum);
						//商品分类名称
						that.$selectors["form_addcategory"][1].val(goodsType.typeName);
						//上级分类名称
						that.$selectors["form_addcategory"][2].val( parentname ).data({
							"id" : goodsType.parentId ,
							"level" : goodsType.typeLevel,
							"currentTypeId": goodsType.typeId
						});
						//商品分类备注
						that.$selectors["form_addcategory"][4].val(goodsType.remark);
						break;
					case 2 :	//查看详情，编辑当前分类
						//商品分类编号
						$form[0].val(goodsType.typeNum);
						//商品分类名称
						$form[1].val(goodsType.typeName);
						//上级分类名称
						
						$form[2].val( parentname ).data({
							"id" : goodsType.parentId ,
							"level" : goodsType.typeLevel,
							"currentTypeId": goodsType.typeId
						});
						//创建时间
						$form[4].val(toDate(goodsType.createTime, "yyyy-MM-dd hh:mm:ss"));
						//商品分类备注
						$form[5].val(goodsType.remark);
						break;
				};
			},
			error: function(){
				//console.log(0)
			},
			complete: function(){
				loading.destory();
			}
		});
		callback && callback();
	},
	/* 更新商品分类下面的子类数据 显示表格  */
	updateCategoryTable : function(treeNode){
		var that = this,
			$selectors = that.$selectors,
			$tabtable = $selectors["$tabtable"];
		$tabtable.trigger("click"); // 先显示table表格 模块
		var id = treeNode.id;

		var params = {
				typeId: id
		};
		
		$.ajax({
			url: '/sysAdmin/goodsTypeAdmin/selectGoodsTypeGrid',
			type: 'post',
			dataType: 'json',
			data: params,
			beforeSend: function(){
				var offset = $selectors["$categorytable"].offset();
				loading = new that.loading({coordinate : { x: offset.left , y : offset.top , w : $selectors["$categorytable"].width() , h : $selectors["$categorytable"].height() }});
			},
			success: function(data){
				var goodsTypeList = data.goodsTypeList;
	            var $tbody = $("#categorytable tbody"),
	                html = '';
	            if (goodsTypeList.length > 0) {
	                for (var i = 0; i < goodsTypeList.length; i++) {
	                    var gtype = goodsTypeList[i];

	                    html += '<tr>';
	                    html += '<td><input type="checkbox" class="simple" data-id="'+gtype.typeId+'"></td>';
	                    html += '<td>'+(i+1)+'</td>';
	                    html += '<td>'+gtype.typeNum+'</td>';
	                    html += '<td>'+gtype.typeName+'</td>';
	                    html += '<td>'+toDate(gtype.createTime, "yyyy-MM-dd hh:mm:ss")+'</td>';
	                    html += '<td>'+gtype.remark+'</td>';
						html += '</td>';
						html += '</tr>';
	                }
	                $tbody.html(html);
	            } else {
	                var $tr = '<tr class="odd"><td colspan="7"> 查无数据！请添加分类！</td></tr>';
	                $tbody.html($tr);
	            }
			},
			error: function(error){
				BSTYUN.dialog.warn("网络异常，请联系管理员");
			},
			complete: function(){
				loading.destory();
			}
		});
	}
};

$(function(){
	BSTMG.productmg.init();
});